package gift4friend.server.core.login;

import gift4friend.server.core.GiftManager.GiftListManager;
import gift4friend.shared.core.User;


import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;

public class LoginManager {

	public static User login(String requestUri) {

		UserService userService = UserServiceFactory.getUserService();
		com.google.appengine.api.users.User googleUser = userService
				.getCurrentUser();
		User realUser;

		if (googleUser != null) {

			realUser = GiftListManager.getUser(googleUser.getEmail());

			// if user did not exist in datastore it will be create :
			if (realUser == null) {
				realUser = new User();
				realUser.setFirstVisit(true);
				realUser.setEmail(googleUser.getEmail());
			} else {
				realUser.setFirstVisit(false);
			}
			realUser.setLoggedIn(true);
			realUser.setLogoutUrl(userService.createLogoutURL(requestUri));
		} else {
			realUser = new User();
			realUser.setLoggedIn(false);
			realUser.setLoginUrl(userService.createLoginURL(requestUri));
		}
		return realUser;
	}

}
